package com.lcf.aop;

import com.lcf.transaction.TransactionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * Created by lancf on 2019/4/25.
 */
//@Component
//@Aspect
public class AopTransaction {

    @Autowired
    protected TransactionUtils transactionUtils;

//    @Pointcut("execution(* com.lcf.service.UserService.add2(..))")
//    public void trans() {
//
//    }

    //异常通知
    @AfterThrowing("execution(* com.lcf.service.UserService.add2(..))")
    public void afterThrowing() {
        System.out.println("事务回滚");
        //获取当前事务并回滚
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }

    //环绕通知
    @Around("execution(* com.lcf.service.UserService.add2(..))")
    public void around(ProceedingJoinPoint proceed) throws Throwable {
        System.out.println("开启事务");
        TransactionStatus transactionStatus = transactionUtils.begin();
        proceed.proceed();//代理调用方法,如果代理的方法抛出异常,则不会执行后面代码
        System.out.println("提交事务");
        transactionUtils.commit(transactionStatus);
    }


}
